import sys

import pymysql
import requests
import json
from datetime import datetime, timedelta
from database_api import DataInsert


def ngfw_data_collection():
    session = requests.session()
    url = "http://10.206.0.69:8080/v1.0/login"
    payload = {
        "username": "xxswasAPI",
        "password": "ftp:7001@Mail"
    }
    headers = {
        "Content-Type": "application/json"
    }
    response = session.post(url, headers=headers, data=json.dumps(payload))
    PHPSESSID = response.cookies.get('PHPSESSID')
    token = response.json()['result']['token']
    headers = {
        "Content-Type": "application/json",
        "Cookie": f"PHPSESSID={PHPSESSID};token={token}"
    }
    payload = [{
        "head": {
            "module": "sec_policy",
            "function": "get_sec_policy",
            "language": "CN",
            "page_index": "1",
            "page_size": "100"
        },
        "body": {
            "sec_policy": [
                {
                    "name": "",
                    "is_detail": "false"

                }
            ]
        },
    }]

    url = "http://10.206.0.69:8080/v1.0/rest"
    response = session.post(url, headers=headers, data=json.dumps(payload)).json()
    data = response["data"]
    record_permit_hitnums = 0
    record_deny_hitnums = 0
    for item in data:
        action = item.get('action')
        hit_nums = int(item.get('hit_num'))
        if action == 'permit':
            record_permit_hitnums += hit_nums
        else:
            record_deny_hitnums += hit_nums
    data = {'阻断数量': record_deny_hitnums, '允许数量': record_permit_hitnums,
            '记录时间': datetime.now().strftime('%Y-%m-%d %H:%M')}
    with open('account.txt', 'a') as f:
        f.write(json.dumps(data, ensure_ascii=False) + "\n")

    try:
        conn = pymysql.Connect(
            user='mobiledj',
            password='ta891qhs',
            host='10.206.0.123',
            port=3306,
            database='mobiledj_security'
        )
    except pymysql.Error as e:
        print(f'Error connecting to MariaDb Platform:{e}')
        sys.exit(1)

    database_api_obj = DataInsert(conn)
    pre_date = datetime.now() - timedelta(days=1)
    database_api_obj.insert_data(datetime.now(), record_permit_hitnums, record_deny_hitnums, pre_date)


ngfw_data_collection()
